📌 寫在 class
裡的函式,專門用來操作該物件的資料
每個人都有一本冒險者手冊
手冊裡寫著:名字、年齡、喜歡的技能
但是光有資料很無聊
所以還要有功能
#include <iostream>
using namespace std;
class Student
{
private:
string name;
int age;
public:
void set(string n, int a)
{
name = n;
age = a;
}
void say()
{
cout << name << ",";
cout << age << " 歲!" << endl;
}
};
int main()
{
Student s;
s.set("小A", 14);
s.say();
return 0;
}
📌 指向目前正在操作的那個物件
小A和小B都有一本手冊
他們都有「自我介紹」這個按鈕
可是如果大家同時按下了按鈕
系統怎麼知道是小A在講,還是小B在講?
這時候,就靠一個隱藏的手電筒
它會照亮正在用手冊的人
#include <iostream>
using namespace std;
class Student
{
private:
string name;
int age;
public:
void set(string name, int age)
{
this -> name = name;
this -> age = age;
}
void say()
{
cout << this -> name << ",";
cout << this -> age << " 歲!" << endl;
}
};
int main()
{
Student s1, s2;
s1.set("小A", 12);
s2.set("小B", 14);
s1.say();
s2.say();
return 0;
}
📌 this
可以想成當下函式放入的變數
📌讓物件能「做事」,不單單只是存放資料
每個物件都有屬於自己的 this
指標
this
指標讓物件知道自己是誰
當有許多個物件同時存在時
this
可以幫助我們區分不同物件的屬性